package cn.hfatec.shms.web.up.upDocument.service;

import java.io.*;
import java.net.InetAddress;
import java.util.Date;
import java.util.List;
import java.util.HashMap;


import cn.hfatec.JsonResponse;
import cn.hfatec.app.AppContext;
import cn.hfatec.shms.constants.ShmsConstant;
import cn.hfatec.shms.constants.ShmsProperties;
import cn.hfatec.shms.exception.NotAuthException;
import cn.hfatec.shms.system.document.model.Document;
import cn.hfatec.shms.system.user.model.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hfatec.base.BaseDao;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.shms.web.up.upDocument.model.UpDocument;
import cn.hfatec.shms.web.up.upDocument.dao.UpDocumentDao;
import cn.hfatec.shms.web.up.upDocument.model.UpDocumentParams;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 *
 * @author hfatec
 * @version 1.0
 *
 * the JAVA code is generate by middlegen
 *
 */
@Service("UpDocumentService")
public class UpDocumentService {

    public static final String BEAN_ID = "UpDocumentService";

    //注入Dao层
    @Resource(name = "UpDocumentDao")
    private UpDocumentDao upDocumentDao;

    //注入BaseDao
    @Resource(name = "BaseDao")
    private BaseDao baseDao;

    /**
     *
     * 查询数据
     *
     * @param upDocumentParams
     * @param page
     *
     */
    @Transactional
    public Table queryUpDocumentTable(UpDocumentParams upDocumentParams, Page page){

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", upDocumentParams);
        return baseDao.queryTableByPage("queryUpDocument", params, page);
    }
    /**
     *
     * 查询数据
     *
     * @param upDocumentParams
     * @param page
     *
     */
    @Transactional
    public Table queryUpDocumentTableUD(UpDocumentParams upDocumentParams, Page page){

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", upDocumentParams);
        return baseDao.queryTableByPage("queryUpDocumentUD", params, page);
    }

    /**
     *
     * 插入数据
     * @param upDocument
     *
     */
    @Transactional
    public void saveUpDocument(UpDocument upDocument) {
        if(upDocument.getId() != null) {
            UpDocument result = getUpDocument(upDocument.getId());
            if(result != null) {
                upDocumentDao.update(upDocument);
            } else {
                upDocumentDao.insert(upDocument);
            }
        } else {
            upDocumentDao.insert(upDocument);
        }
    }

    /**
     *
     * 删除数据
     * @param id
     *
     */
    @Transactional
    public void deleteUpDocument(Integer id) {

        upDocumentDao.delete(id);
    }

    /**
     *
     * 删除数据
     * @param upDocumentList
     *
     */
    @Transactional
    public void deleteUpDocumentBatch(List<String> upDocumentList) {
        for(String id : upDocumentList) {
            String filename= getUpDocument(Integer.valueOf(id)).getDocUrl();
             deleteUpDocument(filename);
            deleteUpDocument(Integer.valueOf(id));
        }
    }

    public void deleteUpDocument(String fileName) {
        ShmsProperties shmsProperties = AppContext.getBean("shmsProperties", ShmsProperties.class);
        String realPath = shmsProperties.getUploadPath();
        String documentPath = shmsProperties.getUploadDocumentPath();
        String uploadFilePath = realPath + documentPath;
        File file = new File(uploadFilePath + "/" + fileName);
        if(file.exists()){
            file.delete();
        }
    }

    /**
     *
     * 根据ID获取数据
     * @param id
     *
     */
    @Transactional
    public UpDocument getUpDocument(Integer id) {

        return upDocumentDao.getUpDocumentById(id);
    }

    /**
     * 插入数据
     * @param file
     * @param request
     */
    @Transactional
    public String saveDocument(UpDocument upDocument,MultipartFile file,HttpServletRequest request) throws NotAuthException, IOException {
        //获取配置的上传文件路径
        ShmsProperties shmsProperties = AppContext.getBean("shmsProperties", ShmsProperties.class);
        String realPath = shmsProperties.getUploadPath();
        String documentPath = shmsProperties.getUploadDocumentPath();
        String uploadFilePath = realPath+"\\"+documentPath;
        User user = (User) request.getSession().getAttribute(ShmsConstant.LOGIN_USER_SESSION_NAME);
        if (user == null) {
            throw new NotAuthException("用户未授权");
        }
        InetAddress addr = InetAddress.getLocalHost();

        String fileName = file.getOriginalFilename();//获取文件名称
        File headPath = new File(uploadFilePath);//服务器文件夹保存路径
        if (!headPath.exists()) {//判断文件夹是否存在，没有存在则创建新文件夹
            headPath.mkdirs();//创建文件夹
        }
        InputStream in = file.getInputStream();
        FileOutputStream out = new FileOutputStream(headPath + "/" + fileName);//文件保存路径
        byte[] buffer = new byte[1024];
        int byteread = 0;
        while ((byteread = in.read(buffer)) > 0) {
            //写入文件
            out.write(buffer, 0, byteread);
        }
        //关闭输入输出流
        in.close();
        out.close();
        //保存上传记录

        upDocument.setOperationDate(new Date());//操作时间
        upDocument.setOperationIp(addr.getHostAddress().toString());//操作Ip
        upDocument.setOperationOrgId(user.getOrgId());
        upDocument.setOperationUserName(user.getUserName());

        upDocument.setDocUrl(fileName);
        upDocument.setOperationUserId(user.getLoginName());
        UpDocument document1 = upDocumentDao.getDocumentByFileName(upDocument.getDocUrl());
        if (document1 != null) {
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "文件"+fileName+"已上传！", "").toString();
        } else {
            saveUpDocument(upDocument);
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, "文件上传成功").toString();
    }
}